<template>
  <div class="add-post">
    <el-form :model="postForm" :rules="postRules" ref="postForm">
      <el-form-item prop="title">
        <el-input v-model="postForm.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item prop="content">
        <mavon-editor style="min-height:600px" v-model="postForm.content"
          ref="md-editor" @imgAdd="handleEditorImgAdd" />
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="info" size="small" @click="goBack()"><i
            class="el-icon-refresh-left"></i>返回
        </el-button>
        <el-button type="success" size="small" @click="submitPost('postForm')"><i
            class="el-icon-edit"></i>发表
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { bindIMG, markdownToHtml } from '@/utils'
import api from '@api'
import { mapState } from 'vuex'
// import { hMixin } from '@mixins'
import { nanoid } from 'nanoid'
export default {
  data() {
    return {
      postForm: {},
      postRules: {
        title: { required: true, message: '请填写文章标题', trigger: 'blur' },
        content: {
          required: true,
          message: '请填写文章内容',
          trigger: 'blur'
        }
      }
    }
  },
  methods: {
    // 图片上传
    async handleEditorImgAdd(pos, file) {
      const formData = new FormData()
      formData.append('files', file)
      await api.upload(formData)
      this.$refs['md-editor'].$img2Url(pos, bindIMG(file.name))
    },
    // 提交文章
    submitPost(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return
        const { success } = await api.addPost(
          this.handlePostForm(this[formName].content)
        )
        if (success) {
          this.$message.success('发布成功')
          this.$router.push({ name: 'discuss' })
        } else {
          this.$message.error('发布失败')
        }
      })
    },
    // 处理文章表单
    handlePostForm(text) {
      console.log('text :', text)
      const htmlcontent = markdownToHtml(text)
      return {
        userid: this.currentUser.id,
        title: this.postForm.title,
        content: this.postForm.content,
        htmlcontent,
        ctime: Date.now(),
        utime: Date.now(),
        id: nanoid()
      }
    }
  },
  // mixins: [hMixin],
  computed: {
    ...mapState(['currentUser'])
  },
  components: {
    mavonEditor
  }
}
</script>

<style lang="less" scoped>
.btns {
  text-align: right;
  .el-button {
    margin-right: 10px;
    i {
      margin-right: 4px;
    }
  }
}
</style>
